package it.koutifaris.travianmap.view.serversview;

import it.koutifaris.travianmap.context.TravianMapContext;
import it.koutifaris.travianmap.dal.TravianServerService;
import it.koutifaris.travianmap.dal.TravianServerService.TravianServer;
import it.koutifaris.travianmap.view.commandlistview.ListElement;
import it.koutifaris.travianmap.view.serversview.ServersView.ServersViewItem;

import java.util.List;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

public class ServersAdapter extends ArrayAdapter<ListElement> {

	private final ServersView view;

	public ServersAdapter(TravianMapContext context, ServersView view) {
		super(context.getActivity(), android.R.layout.simple_list_item_1);
		this.view = view;
		queryForTravianServers(context);
	}

	private int queryForTravianServers(TravianMapContext context) {
		TravianServerService service = context.getServerServiceFactory().travianServerService();

		List<TravianServer> listServers = service.listServers();
		for (TravianServer travianServer : listServers) {
			this.add(new ServersListItem(travianServer));
		}

		this.add(new ListElement("Drop all", new DropAllCommand()));

		service.close();

		return listServers.size();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// view.newViewItem(parent);

		ListElement item = getItem(position);
		ServersViewItem viewItem = view.newViewItem(parent, convertView);
		viewItem.setLabel(item.getLabel());

		if (item instanceof ServersListItem) {
			TravianServer travianServer = ((ServersListItem) item).getTavianServer();
			viewItem.setDeleteClickHandler(new OnDeleteClickListener(travianServer));
		}

		return viewItem.getView();
	}

}
